using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using Keep.Model;
using Keep.Const;
using Serilog;

namespace Keep.Util
{

    public class SqlSugarHelper
    {
        //用单例模式
        public static SqlSugarScope Db;

        public static void SqlSugarInit(string constr, string type, string IsInitDb)
        {
            if (String.IsNullOrEmpty(constr) || String.IsNullOrEmpty(type) || String.IsNullOrEmpty(IsInitDb))
            {
                return;
            }
            DbType t = SqlSugar.DbType.Sqlite;
            if (type.ToUpper().Equals("MYSQL"))
            {
                t = SqlSugar.DbType.MySql;
            }
            if (type.ToUpper().Equals("SQLITE"))
            {
                t = SqlSugar.DbType.Sqlite;
            }
            if (type.ToUpper().Equals("SQLSERVER"))
            {
                t = SqlSugar.DbType.SqlServer;
            }
            bool i = false;
            if (IsInitDb.ToUpper().Equals("TRUE"))
            {
                i = true;
            }
            Db = new SqlSugarScope(new ConnectionConfig()
            {
                ConnectionString = constr,//连接符字串
                DbType = t,//数据库类型 DbType.SqlServer
                IsAutoCloseConnection = true //不设成true要手动close
            },
                  db =>
                  {
                      //(A)全局生效配置点，一般AOP和程序启动的配置扔这里面 ，所有上下文生效
                      //调试SQL事件，可以删掉
                      db.Aop.OnLogExecuting = (sql, pars) =>
                  {
                      Log.Information(sql);//输出sql,查看执行sql 性能无影响

                      //获取原生SQL推荐 5.1.4.63  性能OK
                      //UtilMethods.GetNativeSql(sql,pars)

                      //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                      //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)

                  };

                      //多个配置就写下面
                      //db.Ado.IsDisableMasterSlaveSeparation=true;

                      //注意多租户 有几个设置几个
                      //db.GetConnection(i).Aop
                  });


            if (i)
            {
                //创建数据库
                Db.DbMaintenance.CreateDatabase();
                Db.CodeFirst.InitTables(typeof(User));
                Db.CodeFirst.InitTables(typeof(LinkType));
                Db.CodeFirst.InitTables(typeof(Links));
                Db.CodeFirst.InitTables(typeof(MusicList));
                Db.CodeFirst.InitTables(typeof(MusicOfList));
                User u1 = new()
                {
                    Name = "admin",
                    PassWord = "123456",
                    Status = Static.Enable
                };
                Db.Insertable(u1).ExecuteCommand();
            }
        }

    }

}